package com.billard.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    private final RedisTemplate<String, Object> redisTemplate;
    private final ObjectMapper objectMapper;

    public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.objectMapper = new ObjectMapper();
        this.objectMapper.registerModule(new JavaTimeModule()); // 支持 LocalDateTime
    }

    /**
     * 存对象到 Redis
     * @param key Redis key
     * @param value 对象
     * @param ttlMillis 过期时间（毫秒）
     */
    public void set(String key, Object value, long ttlMillis) {
        try {
            String json = objectMapper.writeValueAsString(value);
            redisTemplate.opsForValue().set(key, json, ttlMillis, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            throw new RuntimeException("Redis 写入失败", e);
        }
    }

    /**
     * 从 Redis 获取对象
     * @param key Redis key
     * @param clazz 对象类型
     * @param <T> 泛型
     * @return 对象或 null
     */
    public <T> T get(String key, Class<T> clazz) {
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) return null;
        try {
            return objectMapper.readValue(obj.toString(), clazz);
        } catch (Exception e) {
            throw new RuntimeException("Redis JSON 解析失败", e);
        }
    }

    /**
     * 删除 Redis key
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 判断 key 是否存在
     */
    public boolean exists(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }
}
